package com.roy.sparkDemos;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;

import java.util.Arrays;

public class SparkWordCountJ {
    /**
     * spark 提交指令
     * ./spark-submit --master yarn --class "com.roy.spark.examples.JavaWordCount" /home/voltdb/sparkapp/sp_wordcount.jar "hdfs://master:9000/roy/test/test.txt" "hdfs://master:9000/roy/sp_out2"
     * @param args
     */
    public static void main(String[] args){
        if (null == args || args.length != 2) {
            System.out.println("Usage: JavaWordCount <file> <putPath>");
            System.exit(1);
        }
        SparkConf sparkConf = new SparkConf();
        sparkConf.setMaster("local[4]");
        sparkConf.setAppName("MySPWordCount");

        JavaSparkContext sc = new JavaSparkContext(sparkConf);
        JavaPairRDD<String, Integer> counts = sc.textFile(args[0])
                .flatMap(line -> Arrays.asList(line.split(" ")).iterator())
                .mapToPair( t ->  new Tuple2<>(t,1))
//                .mapToPair(new PairFunction<String, String, Integer>() {
//                    @Override
//                    public Tuple2<String, Integer> call(String t) throws Exception {
//                        return new Tuple2(t,1);
//                    }
//                })
                .reduceByKey((a,b)-> a+b);
        counts.saveAsTextFile(args[1]);
        sc.stop();
    }
}
